package com.xexun.gpstracker.ui;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import org.json.JSONObject;

import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.CommonRestPath;
import com.xexun.gpstracker.dialog.WizardAlertDialog;
import com.xexun.gpstracker.inter.HttpCallback;
import com.xexun.gpstracker.listener.PrettyTextChangeListener;
import com.xexun.gpstracker.pojo.ResponseData;
import com.xexun.gpstracker.pojo.User;
import com.xexun.gpstracker.util.CommUtil;
import com.xexun.gpstracker.util.HttpUtil;
import com.xexun.gpstracker.util.JsonHttpResponseHelper;
import com.xexun.gpstracker.vo.Session;
import com.xexun.gpstracker.zxing.CaptureActivity;

/**
 * 找回密码获取验证码页面
 *
 * @author huangfei
 */
public class FindPwdActivity extends Activity {
    private ImageButton backButton, scanBtn;
    private Button validButton, nextButton;
    //    private TimeCount timeCount;
    private EditText phoneText, validText, imeiText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_pwd);
//        timeCount = new TimeCount(120000, 1000);

        backButton = (ImageButton) findViewById(R.id.backBtn);
        scanBtn = (ImageButton) findViewById(R.id.scanBtn);
//        validButton = (Button) findViewById(R.id.validBtn);
        nextButton = (Button) findViewById(R.id.nextBtn);
//        phoneText = (EditText) findViewById(R.id.phoneET);
        validText = (EditText) findViewById(R.id.validET);
        imeiText = (EditText) findViewById(R.id.imeiET);

        backButton.setOnClickListener(clickListener);
//        validButton.setOnClickListener(clickListener);
        nextButton.setOnClickListener(clickListener);
        scanBtn.setOnClickListener(clickListener);
        imeiText.addTextChangedListener(new PrettyTextChangeListener(4));
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Session.getInstance().isNeedClose()) {
            FindPwdActivity.this.finish();
            Session.getInstance().setNeedClose(false);
        }
    }

    /**
     * 点击事件
     */
    private OnClickListener clickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.backBtn:
                    FindPwdActivity.this.finish();
                    break;
                case R.id.scanBtn:
                    Intent openCameraIntent = new Intent(FindPwdActivity.this, CaptureActivity.class);
                    openCameraIntent.putExtra("type", "register");
                    startActivityForResult(openCameraIntent, 0);
                    break;
//                case R.id.validBtn:
//                    String phone = phoneText.getText().toString().trim();
//                    if (CommUtil.isBlank(phone) || !Utils.isMobileNO(phone)) {
//                        Toast.makeText(FindPwdActivity.this, R.string.phone_err_, Toast.LENGTH_SHORT).show();
//                    } else {
//                        getValid(phoneText.getText().toString().trim());
//                        timeCount.start();
//                    }
//                    break;
                case R.id.nextBtn:
                    String validCode = validText.getText().toString().trim();
                    String phone = null;//phoneText.getText().toString().trim();
                    String imei = CommUtil.trimSeprator(imeiText.getText().toString().trim(),null);
//                    if (CommUtil.isBlank(phone)) {
//                        Toast.makeText(FindPwdActivity.this, R.string.phoneNO_null_err, Toast.LENGTH_SHORT).show();
//                        return;
//                    }
                    if (CommUtil.isBlank(imei)) {
                        Toast.makeText(FindPwdActivity.this, R.string.imei_null_err, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (CommUtil.isBlank(validCode)) {
                        Toast.makeText(FindPwdActivity.this, R.string.valid_null_err, Toast.LENGTH_SHORT).show();
                        return;
                    }

                    checkAndGo(phone, validCode, imei);

                    break;
            }
        }
    };

    private void checkAndGo(final String phone, final String validCode, final String imei) {
        HttpCallback callback = new HttpCallback() {
            @Override
            public void onStart() {
                CommUtil.showProcessing(FindPwdActivity.this.getWindow().getDecorView(), false, true);
            }

            @Override
            public void onFinish() {
                CommUtil.hideProcessing();
            }

            @Override
            public void onSuccess(ResponseData obj) throws Exception {
                if (obj.getRetcode() == 1) {
                    Intent intent = new Intent(FindPwdActivity.this, UpdatePwdActivity.class);
//                    intent.putExtra("phone", phone);
                    intent.putExtra("validCode", validCode);
                    intent.putExtra("imei", imei);
                    FindPwdActivity.this.startActivity(intent);
                } else {
                    CommUtil.showMsgShort(getString(R.string.check_fpwd_failed));
                }
            }

            @Override
            public void onFailure(String message) throws Exception {

            }
        };
        try {
            JSONObject json = new JSONObject();
            json.putOpt("phone", phone);
            json.putOpt("validCode", validCode);
            json.putOpt("imei", imei);
            HttpUtil.post(CommonRestPath.getFindPwdUrl(), json, new JsonHttpResponseHelper(callback).getHandler());
        } catch (Exception e) {
            CommUtil.hideProcessing();
            CommUtil.showMsgShort(getString(R.string.network_err));
        }
    }


    /* 定义一个倒计时的内部类 */
//    class TimeCount extends CountDownTimer {
//        public TimeCount(long millisInFuture, long countDownInterval) {
//            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
//        }
//
//        @Override
//        public void onFinish() {//计时完毕时触发
//            validButton.setText(R.string.get_valid_hint);
//            validButton.setClickable(true);
//        }
//
//        @Override
//        public void onTick(long millisUntilFinished) {//计时过程显示
//            validButton.setClickable(false);
//            validButton.setText(millisUntilFinished / 1000 + getResources().getString(R.string.time_minus_hint));
//        }
//    }

    /**
     * 获取验证码
     *
     * @param phoneStr
     */
    private void getValid(String phoneStr) {
        User.getValdcode(this, phoneStr, new HttpCallback() {
            @Override
            public void onStart() {
                WizardAlertDialog.getInstance().showProgressDialog(R.string.send_valid_code, FindPwdActivity.this);
            }

            @Override
            public void onFinish() {
                WizardAlertDialog.getInstance().closeProgressDialog();
            }

            @Override
            public void onSuccess(ResponseData obj) {
                Toast.makeText(FindPwdActivity.this, obj.getMsg(), Toast.LENGTH_SHORT).show();
                if (obj.getRetcode() == 0) {
//                    timeCount.cancel();
//                    timeCount.onFinish();
                }
            }

            @Override
            public void onFailure(String message) {
                Toast.makeText(FindPwdActivity.this, message, Toast.LENGTH_SHORT).show();
//                timeCount.cancel();
//                timeCount.onFinish();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            imeiText.setText(scanResult);
        }
    }
}
